function isDocument() {
  return typeof document !== 'undefined'
}
// 解析 http|https://的域名
const parseDomain = function (str) {
  if (!str) return ''
  if (str.indexOf('://') !== -1) str = str.substr(str.indexOf('://') + 3)
  const topLevel = [
    'com',
    'net',
    'org',
    'gov',
    'edu',
    'mil',
    'biz',
    'name',
    'info',
    'mobi',
    'pro',
    'travel',
    'museum',
    'int',
    'areo',
    'post',
    'rec'
  ]
  const domains = str.split('.')
  if (domains.length <= 1) return str
  if (!isNaN(domains[domains.length - 1])) return str
  let i = 0
  while (i < topLevel.length && topLevel[i] !== domains[domains.length - 1]) i++
  if (i !== topLevel.length)
    return domains[domains.length - 2] + '.' + domains[domains.length - 1]
  else {
    i = 0
    while (i < topLevel.length && topLevel[i] !== domains[domains.length - 2])
      i++
    if (i === topLevel.length)
      return domains[domains.length - 2] + '.' + domains[domains.length - 1]
    else
      return (
        domains[domains.length - 3] +
        '.' +
        domains[domains.length - 2] +
        '.' +
        domains[domains.length - 1]
      )
  }
}
const checkdomain = (path) => {
  // 验证是否是域名
  const doname =
    /^([\w-]+\.)+((com)|(net)|(org)|(gov\.cn)|(info)|(cc)|(com\.cn)|(net\.cn)|(org\.cn)|(name)|(biz)|(tv)|(cn)|(mobi)|(name)|(sh)|(ac)| {3}(io)|(tw)|(com\.tw)|(hk)|(com\.hk)|(ws)|(travel)|(us)|(tm)|(la)|(me\.uk)|(org\.uk)|(ltd\.uk)|(plc\.uk)|(in)|(eu)|(it)|(jp))$/

  if (path) {
    return doname.test(document.domain)
  }
}
// 获取window的以及域名
function getOriginHref() {
  if (isDocument) {
    const path = window.location.origin
    return parseDomain(path)
  }
}
export function getOriginHrefORHostName() {
  if (isDocument) {
    const path = window.location.origin
    const hostname = window.location.hostname
    // 判断当前是local还是生产环境
    if (checkdomain(path)) {
      return `.${getOriginHref()}`
    } else {
      return hostname
    }
  }
}
